import * as React from 'react';
import * as ReactDOM from 'react-dom';

interface User {
    name: string
    age: number
    occ: string
}
interface Cate {
    name: string
}
const _console = document.getElementById('console')
const console = {
    log: (info: any) => _console.innerText = info
}
const pageSize = 10
const App = () => {
    const [page, setPage] = React.useState(1)
    const [total, setTotal] = React.useState(0)
    const [list, setData] = React.useState<User[]>([])
    const [cates, setCates] = React.useState<Cate[]>([])
    const [curr,  setCurr] = React.useState(0)
    const app_ref = React.useRef<HTMLDivElement>()

    const loadPageInfo = async () => {
        if (list.length > page * pageSize) {
            // 表示当前页数据已经加载完了， 啥也不干
            return
        }
        if (total && total === list.length) {
            console.log('到头了,别拉了！')
            return
        }
        console.log('加载中...')
        const res: { data: User[], total: number } = await fetch(`./data/page0${page}.json`).then(res => new Promise(reso => setTimeout(() => {
            res.json().then(reso) // 故意拉长时间调试使用
        }, 1000)));
        const data = list.concat(res.data)
        setData(data)
        setTotal(res.total)
        console.log(`加载完成,  ${data.length}/${res.total} `)
    }
    const onChangeCate = (index: number) => {
        setCurr(index)
        setData([])
        setTotal(0)
        setPage(1)
    }

    React.useEffect(function () {
        const cate = cates[curr]
        if (cate) {
            loadPageInfo()
        }
    }, [cates, curr, page])

    React.useEffect(function () {
        fetch(`./data/cate.json`).then(res => res.json()).then(cates => setCates(cates))
    },[])

    setInterval(function () {
        if (app_ref.current) {
            const _app = app_ref.current
            const p = Math.ceil((_app.scrollTop + _app.clientHeight + 50) / (150 * pageSize))
            if (p != page) {
                setPage(p)
            }
        }
    }, 100)

    return <React.Fragment>
        <div className="cate">
            {cates.map((cate, i) => <a className={curr === i ? 'current' : ''} onClick={() => onChangeCate(i)}>{cate.name}</a>)}
        </div>
        <div className="inner" ref={app_ref}>
            {list.map((user, i) => <div className="user-card" key={i}>
                <p>{i + 1}. 姓名: {user.name}, 年龄: {user.age}</p>
                <p>职业: {user.occ}</p>
            </div>)}
            {!!total && total === list.length && <p className="ender">木的啦！</p>}
        </div>
    </React.Fragment>
}

ReactDOM.render(<App />, document.getElementById('app'))


// tsc -t ESNEXT -m amd --jsx 'react' index.tsx